package com.etsoft.comm.generate;

import com.etsoft.comm.tool.*;


public class Render1_Mapper {

	public static void create(GContext ctx) throws Exception {
		String fileStr = ctx.getSampleStr(SampleFile.MapperXML);
		String pk = ctx.getPK();

		// ★ 开始拼字符串
		fileStr = fileStr.replaceFirst("##DaoClassName#", ctx.getClassNameSuffix(SampleFile.Mapper));
		fileStr = fileStr.replace("##ModelClassName#", ctx.getClassNameSuffix(SampleFile.Model));
		// 换 表名
		fileStr = fileStr.replace("##table_name#", ctx.getTable_name());
		// 换 主键
		fileStr = fileStr.replace("##pk#", pk);
		fileStr = fileStr.replace("##project_name#", ctx.project_name);

		// resultMap pk
		{
			String camelName = StringUnit.getCamelName(pk, false);
			String s = "<id column=\"" + pk + "\" jdbcType=\"INTEGER\" property=\"" + camelName + "\" />";
			fileStr = fileStr.replaceFirst("##result_Map_pk#", s);
		}

		MyStringBuilder r_sb = new MyStringBuilder(), u_sb = new MyStringBuilder();
		MyStringBuilder sb = new MyStringBuilder(), sb2 = new MyStringBuilder(), sb3 = new MyStringBuilder();
		for (GContext.DbField f : ctx.getDbFieldList()) {
			sb.append(f.getName()).append(", ");
			if (!pk.equals(f.getName())) {
				String s = "<result column=\"" + f.getName() + "\" jdbcType=\"" + f.getJdbcName() + "\" property=\"" + f.getFName(false) +"\" />";
				r_sb.append(s + System.lineSeparator() + "\t\t");

				s = "<if test=\""+f.getFName(false)+" != null\">"+f.getName()+"=#{"+f.getFName(false)+"},</if>";
				if (ctx.deleteFlagColumn.equals(f.getName())) {
					s = "<!-- " + s + " -->";
				}
				u_sb.append(s + System.lineSeparator() + "\t\t\t");

				sb2.append(f.getName()).append(", ");
				sb3.append("#{"+ f.getFName(false) +"}, ");
			}
		}
		fileStr = fileStr.replaceFirst("##result_Map_list#", r_sb.substring(0, r_sb.length() - 3));
		fileStr = fileStr.replaceFirst("##Base_Column_List#", sb.substring(0, sb.length() - 2));
		fileStr = fileStr.replaceFirst("##Base_Column_List_Without_Pk#", sb2.substring(0, sb2.length() - 2));
		fileStr = fileStr.replaceFirst("##Base_Column_List_Without_Pk1#", sb3.substring(0, sb3.length() - 2));
		fileStr = fileStr.replaceFirst("##updateFieldList#", u_sb.substring(0, u_sb.length() - 4));

		// 输出内容
		FileHelper.writeFile(ctx.getFileFullPath(SampleFile.MapperXML), ctx.getTable_name(), fileStr);
	}
}
